{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Introduction to coupling light into optical fibers\n",
    "\n",
    "In high-contrast imaging we usually only consider the propagation of electric fields in homogenous media, such as air or lenses. In this tutorial we will show how to work with optical fibers, which propagate a different set of mode bases. We start by importing the required libraries and defining some unit constants."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from hcipy import *\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "um = 1e-6"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Usually fibers are small and have compact modes. To couple efficiently into such fibers we need to focus the light onto the fiber face. Therefore we start by making a pupil that we can propagate to a focus."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "num_pupil_pixels = 128\n",
    "D_pupil = 1\n",
    "pupil_grid = make_pupil_grid(num_pupil_pixels, D_pupil)\n",
    "\n",
    "aperture = circular_aperture(D_pupil)(pupil_grid)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Types of fibers\n",
    "The standard fiber is a step-index fiber. A step-index fiber has a small core of high-refractive index surrounded by a cladding of a lower index. This allows for light to be trapped inside the core. In the geometrics optics limit, where the fiber core is many times larger than the wavelength, the trapping inside the fiber happens due to total internal reflection. This is shown in the figure below for two different rays."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "xmax = 10\n",
    "xt = np.linspace(0, xmax)\n",
    "\n",
    "plt.fill_between(xt, -5, 5, color='aliceblue')\n",
    "plt.fill_between(xt, -1, 1, color='lightsteelblue')\n",
    "\n",
    "x = np.linspace(0, 1)\n",
    "for i in range(xmax):\n",
    "    y = (2*(i%2)-1) * 2/(x.max()-x.min()) * (x-x.min()) - (2*(i%2)-1)\n",
    "    plt.plot(x + i, y, 'C1', linewidth=2)\n",
    "\n",
    "x = np.linspace(0, 2)\n",
    "for i in range(5):\n",
    "    y = (2*(i%2)-1) * 2/(x.max()-x.min()) * (x-x.min()) - (2*(i%2)-1)\n",
    "    plt.plot(x + 2 * i, y, 'C2', linewidth=2)\n",
    "    \n",
    "plt.ylim([-10,10])\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In the limit of small cores geometric optics does not work anymore and one needs to consider solving the Maxwell Equations. Due to the invariance of the fiber structure in the propagation direction we can solve the fiber propagation in terms of guided modes. This guided modes will propagate like plane waves but with a different field shape,\n",
    "$$E(\\vec{r}, z)=\\phi\\left(\\vec{r}\\right) e^{i\\beta z}$$\n",
    "\n",
    "Here $\\phi\\left(\\vec{r}\\right)$ is the field distribution and $\\beta$ is the propagation constant.\n",
    "Due to linearity of the Maxwell equations we can use the principle of linear superposition when we have a mixture of modes,\n",
    "$$E = \\sum_n a_n \\phi_n$$\n",
    "\n",
    "In HCIPy the mode solver for guided modes and propagation constants for step-index fibers has been implemented. Now let's look at some types of fibers."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "multimode_fiber_core_radius = 25 * um\n",
    "singlemode_fiber_core_radius = 2 * um\n",
    "fiber_NA = 0.13\n",
    "fiber_length = 10\n",
    "\n",
    "multi_mode_fiber = StepIndexFiber(multimode_fiber_core_radius, fiber_NA, fiber_length)\n",
    "single_mode_fiber = StepIndexFiber(singlemode_fiber_core_radius, fiber_NA, fiber_length)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In this piece of code we created two fibers. A multi-mode fiber with a large core and a single-mode fiber with a small core. Next to the core radius the numerical aperture is also necessary to fully specify the step-index fiber. Finally the length of the fiber is also needed for the propagation. The StepIndexFiber class will calculate the modes on the fly when they are needed, so it is not necessary to initialize it with a wavelength or a grid."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Coupling into fibers\n",
    "We will now create our grid on which we will evaluate the modes. The minimal diameter we need for the grid is 50 $\\mu$m because the multi-mode fiber core radius is 25 $\\mu$m. To sample all features of the modes we need to have sufficient resolution, which is roughly 2 pixels per wavelength. In this case we will use 128 pixels. With the focal plane setup we can setup the propagator too, we choose the focal length in such a way that we match the numerical aperture of the fiber."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "num_focal_pixels = 128\n",
    "D_focus = 2.1 * multimode_fiber_core_radius\n",
    "focal_grid = make_pupil_grid(num_focal_pixels, D_focus)\n",
    "\n",
    "focal_length = D_pupil/(2 * fiber_NA)\n",
    "propagator = FraunhoferPropagator(pupil_grid, focal_grid, focal_length=focal_length)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To propagate the light through the fiber is as easy as propagating through any of the other optical elements. You just call the forward method with the wavefront as parameter. In the code below we propagate a circular aperture to the focal plane and then propagate it through both the multi-mode and single-mode fiber."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "wavelength = 1 * um\n",
    "wf = Wavefront(aperture, wavelength)\n",
    "wf.total_power = 1\n",
    "\n",
    "wf_foc = propagator(wf)\n",
    "\n",
    "wf_mmf = multi_mode_fiber.forward(wf_foc)\n",
    "wf_smf = single_mode_fiber.forward(wf_foc)\n",
    "\n",
    "print(\"Multi-mode fiber throughput {:g}\".format(wf_mmf.total_power))\n",
    "print(\"Single-mode fiber throughput {:g}\".format(wf_smf.total_power))\n",
    "\n",
    "plt.subplot(1,2,1)\n",
    "imshow_field(wf_mmf.power)\n",
    "\n",
    "circ = plt.Circle((0, 0), multimode_fiber_core_radius, edgecolor='white', fill=False, linewidth=2, alpha=0.5)\n",
    "plt.gca().add_artist(circ)\n",
    "plt.xlabel('x (um)')\n",
    "plt.ylabel('y (um)')\n",
    "\n",
    "plt.subplot(1,2,2)\n",
    "imshow_field(wf_smf.power)\n",
    "circ = plt.Circle((0, 0), singlemode_fiber_core_radius, edgecolor='white', fill=False, linewidth=2, alpha=0.5)\n",
    "plt.gca().add_artist(circ)\n",
    "plt.xlabel('x (um)')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The size of the fiber is shown by the white circle. We can see here that the output of both fibers is different. Because the multi-mode fiber supports more modes we can see a more complex output. This is also apparent in the throughput, the multi-mode fiber has a higher throughput. The multi-mode fiber also has advantages when the source is moving due to vibration in your system. This is shown in the next section where the throughput as function of $\\lambda / D$ is calculated."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "tilts = np.linspace(0, 8, 101)\n",
    "\n",
    "smf_coupling = []\n",
    "mmf_coupling = []\n",
    "for tilt in tilts:\n",
    "    wf = Wavefront(aperture * np.exp(1j * tilt * 2 * np.pi * pupil_grid.x), wavelength)\n",
    "    wf.total_power = 1\n",
    "    wf_foc = propagator(wf)\n",
    "    \n",
    "    wf_mmf = multi_mode_fiber.forward(wf_foc)\n",
    "    mmf_coupling.append(wf_mmf.total_power)\n",
    "    wf_smf = single_mode_fiber.forward(wf_foc)\n",
    "    smf_coupling.append(wf_smf.total_power)\n",
    "\n",
    "plt.plot(tilts, smf_coupling, label='Single-mode fiber')\n",
    "plt.plot(tilts, mmf_coupling, label='Multi-mode fiber')\n",
    "plt.xlabel(r'Tilt ($\\lambda / D$)')\n",
    "plt.ylabel('Coupling efficiency')\n",
    "plt.legend()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Fiber wavelength sensitivity\n",
    "\n",
    "Because the multi-mode fiber contains many modes with different propagation constants there is a strong wavelength dependence of the fiber output. This is due to the beating pattern of different modes."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "num_wavelengths = 9\n",
    "bandwidth = 0.01\n",
    "wavelengths = wavelength * (1 + bandwidth * np.linspace(-0.5, 0.5, num_wavelengths))\n",
    "\n",
    "for wi, wave in enumerate(wavelengths):\n",
    "    wf = Wavefront(aperture, wave)\n",
    "    wf.total_power = 1\n",
    "    wf_foc = propagator(wf)\n",
    "    \n",
    "    wf_mmf = multi_mode_fiber.forward(wf_foc)\n",
    "    plt.subplot(3, 3, wi+1)\n",
    "    imshow_field(wf_mmf.power)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The coherence length of the input light determines how long fiber can be before the output start to decohere."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  },
  "level": "beginner",
  "thumbnail_figure_index": -1
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
